import React, {Component} from 'react';
import $http from '../../untils/request'
import {Menu} from 'antd'
import {withRouter} from "react-router-dom";

const {SubMenu} = Menu

class NavList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            menuList: [],
            openKeys: [],
            selectedKeys: [],
        }
    }

    async componentDidMount() {
        await this.getNavList()


    }

    componentWillUnmount() {
        this.setState = () => false;

    }

    render() {
        return (
            <div>
                <Menu mode="inline"
                      onClick={(e) => {
                          this.onMenuItem(e)
                      }}
                      onOpenChange={(e) => {
                          this.onOpenChange(e)
                      }}
                      selectedKeys={this.state.selectedKeys}
                      openKeys={this.state.openKeys}
                >
                    {this.forMatterTree(this.state.menuList)}
                </Menu>
            </div>
        );
    }

    forMatterTree(data) {
        if (data && data.length > 0) {
            return data.map(item => {
                if (item.children && item.children.length > 0) {
                    return (<SubMenu key={item.id} title={item.menuName}>
                        {this.forMatterTree(item.children)}
                    </SubMenu>)
                }
                return (<Menu.Item key={item.id} onClick={() => this.onchangeUrl(item)}>
                    <span>{item.menuName}</span>
                </Menu.Item>)
            })
        }
    }

    onMenuItem(selected) {
        this.setState({
            selectedKeys: selected.key
        })
    }
    onOpenChange(openKeys){
        this.setState({
            openKeys:openKeys
        })
    }
    onchangeUrl(item) {
        this.props.history.push(`/${item.listUrl}`)
    }

    defaultMenu(data, type) {
        const path = this.props.location.pathname.substring(1)
        let obj = null
        const _list = (data, name) => {
            for (let i = 0; i < data.length; i++) {
                if (data[i].children) {
                    _list(data[i].children, name)
                }
                if (data[i].listUrl === name) {
                    obj = data[i]
                    return false
                }
            }
        }
        _list(data, path)
        if (obj) {
            return type === 'pid' ? [obj.pid.toString()] : [obj.id.toString()]
        }
    }

    async getNavList() {
        const res = await $http.get('/getAnthList')
        if (res.status === 200) {
            this.setState({
                menuList: res.data,
                openKeys: this.defaultMenu(res.data, 'pid'),
                selectedKeys: this.defaultMenu(res.data, 'id'),
            })
        }
    }
}

export default withRouter(NavList)
